#include "chatinputtextedit.h"
#include <QDesktopServices>
#include <QDir>
#include "global.h"
#include <QRandomGenerator>

ChatInputTextEdit::ChatInputTextEdit(QWidget *parent) : QTextEdit(parent)
{

}

void ChatInputTextEdit::keyPressEvent(QKeyEvent *e)
{
    if( (e->key() == Qt::Key_Enter||e->key() == Qt::Key_Return) && switch_key_Enter && this->hasFocus() ){
        emit sendMessage();//触发快捷键enter发送消息逻辑，通知主界面发送消息
        return;
    }
    else{
        QTextEdit::keyPressEvent(e);//按照组件默认处理
    }
}

void ChatInputTextEdit::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasImage() || event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    } else {
        QTextEdit::dragEnterEvent(event);
    }
}

void ChatInputTextEdit::dragMoveEvent(QDragMoveEvent *event)
{
    if (event->mimeData()->hasImage() || event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    } else {
        QTextEdit::dragMoveEvent(event);
    }
}
void ChatInputTextEdit::dropEvent(QDropEvent *event)
{

    if (event->mimeData()->hasImage()) {
        QImage image = qvariant_cast<QImage>(event->mimeData()->imageData());

        if (!image.isNull()) {
            insertImage(image);
            event->acceptProposedAction();
            return;
        }
    } else if (event->mimeData()->hasUrls()) {
        QList<QUrl> urls = event->mimeData()->urls();
        for (const QUrl &url : urls) {
            QString filePath = url.toLocalFile();
            QImage image(filePath);
            if (!image.isNull()) {
                insertImage(image);
            }
        }
        event->acceptProposedAction();
        return;
    }
    QTextEdit::dropEvent(event);
}

void ChatInputTextEdit::insertFromMimeData(const QMimeData *source)
{

    if (source->hasImage()) {
        QImage image = qvariant_cast<QImage>(source->imageData());
        if (!image.isNull()) {
            insertImage(image);
            return;
        }
    } else if (source->hasUrls()) {
        QList<QUrl> urls = source->urls();
        for (const QUrl &url : urls) {
            QString filePath = url.toLocalFile();
            QImage image(filePath);
            if (!image.isNull()) {
                insertImage(image);
            }
        }
        return;
    }
    QTextEdit::insertFromMimeData(source);
}

//双击图片显示
void ChatInputTextEdit::mouseDoubleClickEvent(QMouseEvent *event)
{
    QTextCursor cursor = cursorForPosition(event->pos());
    qDebug() << "Cursor position:" << cursor.position();
    QTextBlock block = cursor.block();
    QTextBlock::iterator it;
    for (it = block.begin(); !(it.atEnd()); ++it) {
        QTextFragment fragment = it.fragment();
        qDebug() << "Fragment position:" << fragment.position() << "Length:" << fragment.length();
        if (fragment.contains(cursor.position()) && fragment.charFormat().isImageFormat()) {
            QTextImageFormat imageFormat = fragment.charFormat().toImageFormat();
            QString imageName = imageFormat.name();

                //QString filePath = imagePathMap[imageName];

                QString filePath = QDir::currentPath() + "//" + IMAGE_MSG_PATH + imageName;
                qDebug() << filePath;
                QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
                return;

        }
    }
    QTextEdit::mouseDoubleClickEvent(event);
}


void ChatInputTextEdit::insertImage(const QImage &originalImage)
{

    // 获取 QTextEdit 的可用宽度
    int maxWidth = viewport()->width()/3;

    // 缩放图片以适应宽度
    QImage scaledImage = originalImage.scaledToWidth(maxWidth, Qt::SmoothTransformation);

    QTextCursor cursor = textCursor();
    QTextDocument *document = this->document();

    // 生成一个唯一的图片名称
    // 获取当前时间戳
    qint64 timestamp = QDateTime::currentDateTime().toMSecsSinceEpoch();
    //当前时间戳再加.png结尾
    QString imageName = QString("%1.png").arg(timestamp);
    document->addResource(QTextDocument::ImageResource, QUrl(imageName), scaledImage);
    QTextImageFormat imageFormat;
    imageFormat.setName(imageName);
    cursor.insertImage(imageFormat);
    setTextCursor(cursor);

    QString relativeFilePath = QDir::currentPath() + "//" + IMAGE_MSG_PATH + imageName;
    QFileInfo fileInfo(relativeFilePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists())
    {
        // 如果目录不存在，则创建目录，此处使用mkpath可以创建多级目录（包含中间缺失的目录）
        if (dir.mkpath("."))
        {
            qDebug() << "目录创建成功" << IMAGE_MSG_PATH;
        }
        else
        {
            qDebug() << "创建目录时出错"<< IMAGE_MSG_PATH;
            return;
        }
    }
    if (originalImage.save(relativeFilePath,"PNG"))
    {
        //qDebug() << "图片保存成功" << relativeFilePath;
    }
    else
    {
        qDebug() << "图片保存失败" << relativeFilePath;
    }
}



